package com.lp.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class MybatisUtils {
    private static SqlSessionFactory factory=null;
    static{
        String config="mybatis.xml";
        try {
            InputStream in=Resources.getResourceAsStream(config);
            //创建SqlSessionFactory对象，使用SqlSessionFactoryBuild
            //factory是静态块创建 只有一个
            factory = new SqlSessionFactoryBuilder().build(in);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    //获取SqlSession方法
    public static SqlSession getSqlSession() {
        SqlSession sqlSessiion=null;
        if(factory!=null){
            sqlSessiion=factory.openSession(true);//非自动提交事务
        }
        return sqlSessiion;

    }
}
